package com.imagecollector.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.imagecollector.common.R;
import com.imagecollector.common.constant.TaskConstant;
import com.imagecollector.common.utils.AliOSSUtils;
import com.imagecollector.common.utils.DateTimeUtils;
import com.imagecollector.domain.dto.TaskAbandonRecordDTO;
import com.imagecollector.domain.dto.TaskReceiverRecordDTO;
import com.imagecollector.domain.entity.*;
import com.imagecollector.domain.dto.PictureDTO;
import com.imagecollector.domain.vo.ScenicAndExibitorNames;
import com.imagecollector.domain.vo.TaskAndExibitorNames;
import com.imagecollector.domain.vo.TaskVo;
import com.imagecollector.mapper.TaskReceiverRecordMapper;
import com.imagecollector.service.IAppletTaskService;
import com.imagecollector.service.impl.PictureServiceImpl;
import com.imagecollector.service.impl.TaskAbandonRecordServiceImpl;
import com.imagecollector.service.impl.TaskReceiverRecordServiceImpl;
import com.imagecollector.service.impl.TaskSubmitRecordServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 任务表 前端控制器
 * </p>
 *
 * @author wrf
 * @since 2024-07-31
 */
@RestController
@RequestMapping("user/appletTask")
@Api(tags = "小程序用户操作相关接口")

@Slf4j
public class AppletTaskController {
    @Autowired
    private IAppletTaskService taskService;
    @Autowired
    private TaskAbandonRecordServiceImpl taskAbandonRecordService;
    @Autowired
    TaskReceiverRecordServiceImpl taskReceiverRecordService;
    @Autowired
    private TaskReceiverRecordMapper taskReceiverRecordMapper;


    @Autowired
    private AliOSSUtils aliOSSUtils;

    @ApiOperation(value = "任务列表")
    @GetMapping("/list")
    public R list(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(defaultValue = "") Integer districtId) {

        IPage<TaskVo> taskVoIPage = taskService.selectPage(pageNum, pageSize, districtId);
        return R.success().data("data", taskVoIPage);
    }

    /**
     *
     * @param taskId     任务id
     * @param customerServiceRemarkScenic   景区名称
     * @param customerServiceRemarkExhibits 展品名称
     * @return
     */
    @ApiOperation(value = "任务详情")
    @GetMapping("/detail")
    public R detail(@RequestParam Integer taskId, @RequestParam(defaultValue = "") String customerServiceRemarkScenic, @RequestParam(defaultValue = "") String customerServiceRemarkExhibits) {
        TaskVo taskVo = taskService.selectDetail(taskId);
        // 获取客服标注过的展品
        List<ScenicAndExibitorNames> exhibitorNames = taskService.selectExhibitorNames(customerServiceRemarkScenic, customerServiceRemarkExhibits);
        TaskAndExibitorNames taskAndExibitorNames = new TaskAndExibitorNames();
        taskAndExibitorNames.setTaskVo(taskVo);
        taskAndExibitorNames.setExibitorNames(exhibitorNames);
        return R.success().data("data", taskAndExibitorNames);
    }


    @ApiOperation(value = "任务接取")
    @PostMapping("/receive")
    @ResponseBody
    public R receive(@RequestBody @Valid TaskReceiverRecordDTO taskReceiverRecordDTO) {
        QueryWrapper<TaskReceiverRecord> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("task_id", taskReceiverRecordDTO.getTaskId());
        queryWrapper2.eq("user_id", taskReceiverRecordDTO.getUserId());
        queryWrapper2.eq("status", TaskConstant.TASK_STATUS_RECEIVED);
        List<TaskReceiverRecord> taskReceiverRecords = taskReceiverRecordService.list(queryWrapper2);

        if (!taskReceiverRecords.isEmpty()){
            return R.fail(400,"您已接取该任务，请先完成再接取！");
        }

        QueryWrapper<TaskAbandonRecord> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("task_id", taskReceiverRecord.getTaskId());   加上这个表示同一个任务取消后禁止接取
        queryWrapper.eq("user_id", taskReceiverRecordDTO.getUserId());
        queryWrapper.orderByDesc("create_time");
        List<TaskAbandonRecord> taskAbandonRecords = taskAbandonRecordService.list(queryWrapper);
        if ( taskAbandonRecords != null && !taskAbandonRecords.isEmpty()) {
            TaskAbandonRecord taskAbandonRecord = taskAbandonRecords.get(0);
            long seconds = DateTimeUtils.secondsBetween(taskAbandonRecord.getCreateTime(), LocalDateTime.now());
            if (seconds < 10){
                return R.fail(400,"放弃任务后10s内不能接取新任务");
            }else {
                QueryWrapper<TaskReceiverRecord> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("user_id", taskReceiverRecordDTO.getUserId());
                queryWrapper1.eq("status", TaskConstant.TASK_STATUS_RECEIVED);
                if (taskReceiverRecordService.count(queryWrapper1) > 5){
                    return R.fail(400,"可接取任务已满");
                }else {
                    taskService.receive(taskReceiverRecordDTO);
                }
            }

        }else {
            taskService.receive(taskReceiverRecordDTO);

        }
        return R.success();
    }


    @ApiOperation(value = "提交任务")
    @PostMapping("/submit")
    @ResponseBody
    public R submit(@RequestBody @Valid PictureDTO pictureDTO) throws JsonProcessingException {


        // 判断所提交的任务是否已过期
        // 先查询是否有过期未提交的任务
        TaskReceiverRecord taskReceiverRecord = taskReceiverRecordMapper.expiredTask(pictureDTO.getReceiverRecordId(),pictureDTO.getUserId());
        if (taskReceiverRecord != null){
            // 先将接受表更新状态为-3
            taskReceiverRecord.setStatus(TaskConstant.TASK_STATUS_EXPIRED);
            taskReceiverRecordMapper.updateById(taskReceiverRecord);
            // 往放弃表添加数据
            TaskAbandonRecord taskAbandonRecord = new TaskAbandonRecord();
            taskAbandonRecord.setTaskId(taskReceiverRecord.getTaskId());
            taskAbandonRecord.setUserId(taskReceiverRecord.getUserId());
            taskAbandonRecord.setReceiverRecordId(taskReceiverRecord.getId());
            taskAbandonRecordService.save(taskAbandonRecord);
            return R.fail(400,"任务已过期，请重新接取任务");

        }
        Task task = taskService.getById(pictureDTO.getTaskId());
        Objects.requireNonNull(task, "任务已不存在");
        if (pictureDTO.getUrl().size() != task.getPicNum()){
            return R.fail().msg("提交的图片数量不满足任务要求，请重新提交");
        }
        taskService.submit(pictureDTO, pictureDTO.getReceiverRecordId());
        return R.success();
    }


    @ApiOperation(value = "放弃任务")
    @DeleteMapping("/giveup")
    @ResponseBody
    public R giveup(@RequestBody @Valid TaskAbandonRecordDTO taskAbandonRecordDTO) {

        taskService.giveup(taskAbandonRecordDTO);
        return R.success();
    }


    /**
     *
     * @param pageNum
     * @param pageSize
     * @param districtId
     * @param userId
     * @param status    任务状态，2表示已接取未完成，3表示已完成待审核，4表示审核通过待打款，5表示审核不通过，7已打款
     * @return
     */
    @ApiOperation(value = "我的任务列表")
    @GetMapping("/myTaskList")
    public R myTaskList(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(defaultValue = "") Integer districtId,
                        @RequestParam Integer userId,@RequestParam(defaultValue = "2") Integer status) {

        IPage<TaskVo> taskVoIPage = taskService.selectMyTaskPage(pageNum, pageSize, districtId, userId, status);
        return R.success().data("data", taskVoIPage);
    }


    @ApiOperation(value = "图片上传")
    @PostMapping("/upload")
    public R upload(MultipartFile image) throws IOException {
        String url = aliOSSUtils.upload(image);
        log.info("存入阿里云oss的地址为：{}", url);
        return R.success().data("url", url);
    }
}
